package cn.tedu.web.mapper;

import java.math.BigDecimal;
import java.util.List;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import cn.tedu.web.entity.Wallet;
import cn.tedu.web.entity.WalletAccount;

/**
 * <p>
 * 【我的钱包】 Mapper 接口
 * </p>
 *
 * @author issen
 * @since 2021-10-23
 */
@Mapper
public interface WalletMapper extends BaseMapper<Wallet> {
    // 检查用户的钱包信息是否存在
    @Select("SELECT COUNT(1) FROM ec_wallet WHERE uid = #{id}")
    public boolean exists(@Param("id") Integer id);

    // 检查指定用户的支付密码是否正确
    @Select("SELECT COUNT(1) FROM ec_wallet WHERE uid = #{id} AND `password` = MD5(#{p})")
    public boolean checkPassword(@Param("id") Integer id, @Param("p") String password);

    // 当执行扣款之前, 检查余额是否足以支付相应的金额
    @Select("SELECT COUNT(1) FROM ec_wallet WHERE uid = #{id} AND amount - ABS(#{a}) >=0")
    public boolean isSufficient(@Param("id") Integer id, @Param("a") Double amount);

    // 根据用户的ID查询余额
    @Select("SELECT amount FROM ec_wallet WHERE uid = #{id}")
    public BigDecimal findAmountById(@Param("id") Integer id);

    /**
     * 初始化用户的支付密码
     *
     * @param id       指定的用户的ID，参考 user 表的主键
     * @param password 用户的支付密码
     * @return
     */
    @Insert("INSERT INTO ec_wallet VALUES(#{uid}, 0, MD5(#{pwd}))")
    public Integer init(@Param("uid") Integer id, @Param("pwd") String password);

    /**
     * 更新钱包中的金额
     *
     * @param id       指定的用户的ID，参考 user 表的主键
     * @param password 用户的支付密码
     * @param amount   充值金额或者扣款金额, 正数：表示充值, 负数：表示扣款
     */
    @Update("UPDATE ec_wallet SET amount = amount + #{a} WHERE uid = #{uid} AND `password` = MD5(#{pwd})")
    public Integer updateAmount(@Param("uid") Integer id, @Param("pwd") String password, @Param("a") Double amount);

    /**
     * 记录账目流水
     */
    @Insert("INSERT ec_wallet_account (`uid`, `amount`, `type`, `description`) VALUES (#{uid}, #{amount}, #{type}, #{description});")
    public Integer insertWalletAccount(WalletAccount account);

    /**
     * 查询指定账户的交易流水
     */
    @Select("SELECT amount, description, type, time FROM ec_wallet_account WHERE uid = #{uid} ORDER BY time DESC")
    public List<WalletAccount> findAll(@Param("uid") Integer id);
}
